package com.example.flex.controller;

import com.example.flex.domain.AccountDO;
import com.example.flex.domain.table.AccountTableDef;
import com.example.flex.service.AccountService;
import com.mybatisflex.crypto.AlgorithmType;
import com.mybatisflex.crypto.CryptoManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@Validated
@RestController
public class DemoController {

    @Autowired
    private AccountService accountService;

    @PostMapping("/save")
    public AccountDO save(@RequestBody AccountDO accountDO) {
        accountDO.setGmtCreate(System.currentTimeMillis());
        accountDO.setGmtUpdate(System.currentTimeMillis());
        accountDO.setDeleted(0L);
        accountService.save(accountDO);
        return accountDO;
    }


    @GetMapping("/get")
    public AccountDO get(@RequestParam Long id) {
        return accountService.getById(id);
    }

    @GetMapping("/query")
    public List<AccountDO> query(@RequestParam String keyword, @RequestParam int type) {
        try {
            CryptoManager.skipDecrypt();
            return accountService.queryChain()
                    .where(AccountTableDef.ACCOUNT.DC.in(CryptoManager.encryptAll(AlgorithmType.Symmetric, keyword), type == 1))
                    .and(AccountTableDef.ACCOUNT.FDC.in(CryptoManager.encryptAll(AlgorithmType.Asymmetric, keyword), type == 2))
                    .and(AccountTableDef.ACCOUNT.ZHY.in(CryptoManager.encryptAll(AlgorithmType.Digest, keyword), type == 3))
                    .list();
        } finally {
            CryptoManager.restoreDecrypt();
        }
    }

    @PostMapping("/update")
    public boolean update(@RequestBody AccountDO accountDO) {
        accountDO.setGmtUpdate(System.currentTimeMillis());
        return accountService.updateById(accountDO);
    }

    @PostMapping("/remove")
    public boolean remove(@RequestParam Long id) {
        return accountService.updateChain()
                .from(AccountTableDef.ACCOUNT)
                .set(AccountTableDef.ACCOUNT.DELETED, id)
                .set(AccountTableDef.ACCOUNT.GMT_UPDATE, System.currentTimeMillis())
                .where(AccountTableDef.ACCOUNT.ID.eq(id))
                .update();
    }


}
